package com.amt.iptvsetting.business.virtual;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.amt.iptvsetting.R;
import com.app.common.activity.BaseActivity;
import com.didi.virtualapk.PluginManager;

import org.jetbrains.annotations.Nullable;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

@Route(path = "/zhouwd/virtual_apk_activity")
public class VirtualAPKActivity extends BaseActivity {

    private static final String TAG = VirtualAPKActivity.class.getSimpleName();

    private static final int PERMISSION_REQUEST_CODE_STORAGE = 20191106;

    private ProgressDialog progressDialog;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_virtual);
        ButterKnife.bind(this);

        progressDialog = new ProgressDialog(this);
        
        if (!hasPermission()) {
            requestPermission();
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (PERMISSION_REQUEST_CODE_STORAGE == requestCode) {
            if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                finish();
            }
            return;
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }


    private boolean hasPermission() {

        Log.d(TAG,"hasPermission");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            return checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;
        }

        return true;
    }

    private void requestPermission() {

        Log.d(TAG,"requestPermission");

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE_STORAGE);
        }

    }


    @OnClick(R.id.activity_virtual_load_plugin)
    public void onActivityVirtualLoadPluginClicked() {
        
        
        Observable.create((ObservableOnSubscribe<String>) emitter -> {

            File apk = new File(getFilesDir(), "VirtualApkPlugin.apk");
            if (!apk.exists()) {
                InputStream inputStream = null;
                FileOutputStream outputStream = null;
                try {
                    inputStream = getAssets().open("plugin/VirtualApkPlugin.apk", 2);
                    outputStream = new FileOutputStream(apk);
                    byte[] buf = new byte[1024];
                    int len;

                    while ((len = inputStream.read(buf)) > 0) {
                        outputStream.write(buf, 0, len);
                    }
                    
                    Log.i(TAG, "Loaded plugin from assets: " + apk);
                } catch (Exception e) {
                    e.printStackTrace();
                    Log.e(TAG, "onActivityVirtualLoadPluginClicked: ", e);
                    emitter.onError(e);
                } finally {
                    if (inputStream != null) {
                        inputStream.close();
                    }
                    
                    if (outputStream != null) {
                        outputStream.close();
                    }
                }
            }

            PluginManager pluginManager = PluginManager.getInstance(this);
            pluginManager.loadPlugin(apk);
            emitter.onNext("hahaha");
            emitter.onComplete();
        })
        .observeOn(Schedulers.io())
        .subscribeOn(AndroidSchedulers.mainThread())
        .subscribe(new Observer<String>() {
            @Override
            public void onSubscribe(Disposable d) {
                Log.i(TAG, "onSubscribe: ");
                //progressDialog.show();
            }

            @Override
            public void onNext(String s) {
                Log.i(TAG, "onNext: s -> " + s);
            }

            @Override
            public void onError(Throwable e) {
                Log.i(TAG, "onError: ");
                progressDialog.hide();
            }

            @Override
            public void onComplete() {
                Log.i(TAG, "onComplete: ");
                //progressDialog.hide();
            }
        });
    }

    @OnClick(R.id.activity_virtual_start_plugin)
    public void onActivityVirtualStartPluginClicked() {
        final String pkg = "com.app.virtualapkplugin";
        if (PluginManager.getInstance(this).getLoadedPlugin(pkg) == null) {
            Toast.makeText(this, "插件未加载..", Toast.LENGTH_SHORT).show();
            return;
        }

        Intent intent = new Intent();
        intent.setClassName(this, "com.app.virtualapkplugin.MainActivity");
        startActivity(intent);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (progressDialog != null) {
            progressDialog.dismiss();
            progressDialog = null;
        }
    }
}
